/*   This file is part of jTopaz.
    http://gcl.cis.udel.edu/projects/jtopaz
    Copyright (C) 2009 University of Delaware

    jTopaz is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    jTopaz is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of                                                        
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with jTopaz.  If not, see <http://www.gnu.org/licenses/>.
*/

/*
Contains functions for defining the toggle actions of the trees.
Uses buildLocalTree and buildTree
*/
var username;
var passwd;
var myProxyServer;
var client;
var listContents;
var transferCount = 0;
var lastUpdated=0;
var infoClientStarted=false
var transferClientStarted=false;
var uploadClientStarted=false;
var loginDone=false;

/*
called when the page is loaded.  gets the two trees, and set their toggleOpenState methods as their respective new methods
*/
function setToggle() {


	var tree = document.getElementById("localTree");

tree.view.toggleOpenState=myToggleOpenState;

	tree = document.getElementById("remoteTree");
	tree.view.toggleOpenState=myRemoteToggleOpenState;

}

/*
called whenever a tree item is clicked.  (for some reason my toggle functions would stop working after awhile when user scrolled around.  This is in here to try to fix that
*/
function toggled() {
	setToggle();
}

/*
ToggleOpenState method for the local tree.  takes the index clicked as it's parameter.  Creates an nsILocalFile xpcom object, appends subdirectories, and opens it.
*/
function myToggleOpenState(index) {
	
	//get the localTree xul element
	var localTree = document.getElementById("localTree");
	
	//get the name of the clicked element
	var id = localTree.view.getCellValue(index, localTree.columns.getFirstColumn());
	
	//get that element
	var container = document.getElementById("item " + id);
	
	//if it's not open
	if(! localTree.view.isContainerOpen(index)) {
		
		//get the element where the children will be placed
		var placement = document.getElementById(id + " treechildren");
		//call buildLocalTree
		buildLocalTree(id, placement);

		//set it as open
		container.setAttribute("open", true);
		
		//wish this wasn't necessary.
		//remove and reappend the child
		var contents = document.getElementById("localContents");
		var parent = contents.parentNode;
		parent.removeChild(contents);
		parent.appendChild(contents);
	}
	
	//otherwise just close it
	else {
		container.setAttribute("open", false);
	}
}

/*
Toggle function for remote tree
*/
function myRemoteToggleOpenState(index) {

	//get the remote Tree
	var remoteTree = document.getElementById("remoteTree");
	
	//get the name that is currently clicked
	var id = remoteTree.view.getCellValue(index, remoteTree.columns.getFirstColumn());
	
	//get the container element
	var container = document.getElementById("remote item " + id);
	
	//if it's not open
	if(! remoteTree.view.isContainerOpen(index)) {
		
		
		var childrenId = id + " treechildren";
		
		var placement = document.getElementById(childrenId);
		
		
		var GridFTPClient = Components.classes['@pmcclory.gcl.udel.edu/gridftpclient;1']
                                    .getService().wrappedJSObject;
		
		//update the client
		GridFTPClient.client.update();
	
		//change to the other directory
		GridFTPClient.client.changeDir(id);
		
		//update again
		GridFTPClient.client.update();
		
		//rebuild the tree
		buildTree(placement, false);
		
		//set the container as open
		container.setAttribute("open", true);
	}
	
	//otherwise simply close the container
	else {
		container.setAttribute("open", false);	
	}
}

/*
updates the local tree.  Takes the directory to display and the parent location to append the info to.
*/
function buildLocalTree(startDirStr, parent){
	
	//alert("using this build");
	//create the file from the dir string
	var startDir = Components.classes["@mozilla.org/file/local;1"]
                     .createInstance(Components.interfaces.nsILocalFile);	
   
    startDir.initWithPath(startDirStr);
   
   	//get the dir contents
    var enumerator = startDir.directoryEntries;
    
    //loop through the contents
    while(enumerator.hasMoreElements()) {
    	var next = enumerator.getNext();
    	var file = next.QueryInterface(Components.interfaces.nsIFile);
    	
    	//check the file exists
    	if (file.exists()){
    		

    		
    			//create a tree item
    			var item = document.createElement("treeitem");
    			

    			item.setAttribute("id", "item " + file.path);
    			item.setAttribute("value", file.path);
    			//item.setAttribute("open", "false");
    		
    			//create a tree row
    			var row = document.createElement("treerow");
    			
    			//row.setAttribute("id", file.path);
    			row.setAttribute("value", file.path);
    		
    			var cell = document.createElement("treecell");
    			cell.setAttribute("id", file.path);
    			cell.setAttribute("label", file.leafName);
    			cell.setAttribute("value", file.path);	
    			
    			row.appendChild(cell);
    			if (file.isDirectory()) {
	    			cell.setAttribute("src", "chrome://sample/content/folder.gif");
	    			var cell2 = document.createElement("treecell");
	    			cell2.setAttribute("label", "-");
	    			cell2.setAttribute("id", file.path + " local size");
	    			cell2.setAttribute("value", 0);
	    			row.appendChild(cell2);
    			}
    			
    			else {
    				var cell2 = document.createElement("treecell");
    		
    			var size = file.fileSize;
    			if (size >= 1073741824) {
    				size = size/1073741824;
    				size = size*100;
    				size = Math.floor(size);
    				size = size/100;
    				cell2.setAttribute("label", size + " gB");
    				cell2.setAttribute("id", file.path + " local size");
    				cell2.setAttribute("value", file.fileSize);
    			}
    			
    			else if (size >= 1048576) {
    				size = size/1048576;
    				size = size * 100;
    				size = Math.floor(size);
    				size = size/100;
    				cell2.setAttribute("label", size + " mB");
    				cell2.setAttribute("id", file.path + " local size");
    				cell2.setAttribute("value", file.fileSize);

    			}
    			
    			else {
    				size = size/1024;
    				size = size * 100;
    				size = Math.floor(size);
    				size = size/100;
    				cell2.setAttribute("label", size + " kB");
    				cell2.setAttribute("id", file.path + " local size");
    				cell2.setAttribute("value", file.fileSize);

    			}
    			row.appendChild(cell2);
    			}	
    			//alert(file.path);
    			//append the new elements to the DOM
    			
    			var cell3 = document.createElement("treecell");
    			var time = new java.util.Date(file.lastModifiedTime);
    			cell3.setAttribute("label", time.toString());
    			cell3.setAttribute("id", file.path + " local date");
    			cell3.setAttribute("value", file.lastModifiedTime);
    			row.appendChild(cell3);
    			item.appendChild(row);
    			//row.appendChild(cell2);
    			item.appendChild(row);
				parent.appendChild(item);

    	}
    
    }
}

/*
given a tree name, returns the actual tree in the document
*/
function getTree(treeName) {
	var tree = document.getElementById(treeName);
	return tree;
}

/*
given a tree name, returns the index that is currently selected.
*/
function getSelectedIndex(treeName) {
	var tree = getTree(treeName);
	var index = tree.view.selection.currentIndex;
	return index;
}

/*
given a tree, returns the value of the currently selected element
*/
function getSelectedValue(treeName, index) {
	var tree = getTree(treeName);
	try {
		var value = tree.view.getCellValue(index, tree.columns.getFirstColumn());
		return value;
	}
	catch(e) {
		alert("something went wrong");
		alert(e);
	}
}

/*
given a tree, returns the text of the currently selected index
*/
function getSelectedText(treeName, index) {
	var tree = getTree(treeName);
	return tree.view.getCellText(index, tree.columns.getFirstColumn());
}

/*
builds the remote tree.  takes the parent element, and the currentlySelected dir.  gets the contents and appends it 
*/
/*
function buildTree(parent, currentlySelected) {
	
	//load the component.
	var GridFTPClient = Components.classes['@pmcclory.gcl.udel.edu/gridftpclient;1']
                                    .getService().wrappedJSObject;
     
     
    //update the info client                               
	GridFTPClient.client.update();
	
	//get the contents
	var files = GridFTPClient.client.list();
	
	//loop through the files
	for(var i=0; i<files.length; i++) {
	
		if (! files[i].isDirectory()) {
			
			if (currentlySelected == true) {
				var item = document.createElement("treeitem");
				var row = document.createElement("treerow");
				var cell = document.createElement("treecell");
				cell.setAttribute("label", files[i].getName());
				cell.setAttribute("value", GridFTPClient.client.getCurrentDir() + "/"  + files[i].getName());
				
				var cell2 = document.createElement("treecell");
				cell2.setAttribute("label", "-");
				row.appendChild(cell);
				row.appendChild(cell2);
				//item.appendChild(row);
				//parent.appendChild(item);
			}
		}
		
		else if ((files[i].getName() != ".") && (files[i].getName() != ".."))  {
			var item = document.createElement("treeitem");
			GridFTPClient.client.update();
			var value = GridFTPClient.client.getCurrentDir() + "/" + files[i].getName()
			
			
			item.setAttribute("id", "remote item " + value);
			var row = document.createElement("treerow");
			var cell = document.createElement("treecell");
			
			cell.setAttribute("label", files[i].getName());
			cell.setAttribute("id", value);
			cell.setAttribute("value", value);
			cell.setAttribute("src", "chrome://sample/content/folder.gif");
			
			var size = files[i].getSize();
			
			var cell2 = document.createElement("treecell");
			cell2.setAttribute("label", size);
			row.appendChild(cell);
			row.appendChild(cell2);
			
		}
		
		var cell3 = document.createElement("treecell");
		cell3.setAttribute("label", "test");
		row.appendChild(cell3);
		item.appendChild(row);
		parent.appendChild(item);
	}
}
*/
